/*
 * lambx - Ambx lighting controller
 *
 * Copyright (C) 2010
 *     paul nolan (caribo@caribo.co.uk)
 *
 * This program is free software; you can
 * redistribute it and/or modify it under the terms
 * of the GNU General Public License as published by
 * the Free Software Foundation, version 2 of the
 * License.
 *
 */
 
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <usb.h>
#include "lambx.h"

/* GLOBAL variables */

struct usb_device *usb_dev;
struct usb_dev_handle *usb_handle;

/* -----------------------------------------------------
  Name:		ambx_set_light_color		
  Function:	set color of specific ambx light
  ----------------------------------------------------- */
void ambx_set_light_color(int light, int r, int g, int b) {
	char buf[] = { 0xA1, light, AMBX_SET_LIGHT_COLOR, r, g, b };
	usb_interrupt_write(usb_handle, AMBX_ENDPOINT_OUT, buf, 6, 0);
}

static struct usb_device *device_init(void)
{
    struct usb_bus *usb_bus;
    struct usb_device *dev;

    usb_init();
    usb_find_busses();
    usb_find_devices();

    for (usb_bus = usb_busses;
         usb_bus;
         usb_bus = usb_bus->next) {
        for (dev = usb_bus->devices;
             dev;
             dev = dev->next) {
            if ((dev->descriptor.idVendor
                  == USB_VENDOR_ID) &&
                (dev->descriptor.idProduct
                  == USB_PRODUCT_ID))
                return dev;
        }
    }
    return NULL;
}

int main(int argc, char **argv)
{
	float r[5],g[5],b[5];
	double prev[] = {0,0,0,0,0};
	int ambx_light[] = {AMBX_LEFT,
		AMBX_WWLEFT,
		AMBX_WWCENTER,
		AMBX_WWRIGHT,
		AMBX_RIGHT};
	int red,green,blue;
	int loop = 0;

	usb_dev = device_init();
	if (usb_dev == NULL) {
		fprintf(stderr, "amBX device not found\n");
		goto exit;
	}

	printf("Vendor: %x\n",usb_dev->descriptor.idVendor);
	printf("Product: %x\n",usb_dev->descriptor.idProduct);

	usb_handle = usb_open(usb_dev);
	if (usb_handle == NULL) {
		fprintf(stderr, "Cannot open amBX device\n");
		goto exit;
	}

	if (usb_claim_interface(usb_handle,0)) {
		fprintf(stderr,
		"Not able to claim the amBX device\n");
		goto exit;
	}

	while (scanf("%f %f %f %f %f %f %f %f %f %f %f %f %f %f %f",
		&r[0],&g[0],&b[0],
		&r[1],&g[1],&b[1],
		&r[2],&g[2],&b[2],
		&r[3],&g[3],&b[3],
		&r[4],&g[4],&b[4]) ) {

		for(loop=0;loop<5;loop++) {
			red = (int) (r[loop] * 255);	
			green = (int) (g[loop] * 255);	
			blue = (int) (b[loop] * 255);	
/*
			if ( (double) ((red<<16) & (green<<8) & blue) != prev[loop] ) {
*/
				ambx_set_light_color(ambx_light[loop],red,green,blue);
/*
				prev[loop] = (double) ( (red<<16) & (green<<8) & blue);
			}
*/
		}
	}

exit:
    usb_close(usb_handle);
    return 1;
}

